package com.qian.ddj.pay.controller;


import com.qian.api.ddj.model.*;
import com.qian.api.ddj.service.IDaiFuOrderService;
import com.qian.api.ddj.service.IUserService;
import com.qian.api.ddj.util.RSASignUtils;
import com.qian.api.ddj.util.SignUtils;
import com.qian.ddj.pay.model.OrderDf;
import com.qian.ddj.pay.model.QueryOrderDf;
import com.yaowk.api.common.BaseException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping("/ddj/withdraw")
@Api("代付接口")
@Slf4j
/**
 * @author quziwei
 */
public class WithDrawController {
    @Autowired
    private IDaiFuOrderService daiFuOrderService;
    @Autowired
    private IUserService userService;



    @PostMapping("/query")
    public QueryReturnModel query(QueryModel queryModel){
        QueryReturnModel model = new QueryReturnModel();
        if (!StringUtils.isEmpty(queryModel.getUserId()) && !StringUtils.isEmpty(queryModel.getSign())){
            User user = daiFuOrderService.query(queryModel.getUserId());
            if (!ObjectUtils.isEmpty(user)){
                if (!StatusDict.CLOSE.equals(user.getStatus())){
                    Map map = queryModel.getMap();
                    String sign = (String) map.get("sign");
                    sign = sign.replaceAll("%2B","\\+");
                    System.out.println();
                    map.remove("sign");
                    byte[] data = null;
                    try {
                        data =  SignUtils.params(map).getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        throw new BaseException("签名校验过程异常！");

                    }
                    try {
                        if (RSASignUtils.verify(data,user.getPublicKey(),sign)){
                            model.setBalance(String.valueOf(user.getBalance().doubleValue() - user.getDfFee().doubleValue()));
                            model.setUserId(user.getUsername());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {

                    throw new BaseException("商户已停用");

                }
            }else {
                throw new BaseException("商户不存在");
            }
        }else {
            throw new BaseException("请填写完整参数");
        }

        return model;
    }

    @PostMapping("/")
    public WitthdrawReturn placeOrder(WithdrawModel model){
        WitthdrawReturn witthdrawReturn = new WitthdrawReturn();
        if (!StringUtils.isEmpty(model.getUserId()) && !StringUtils.isEmpty(model.getSign())){
            User user = new User();
            user.setUsername(model.getUserId());
            user = userService.findOne(user);
            if (!StatusDict.CLOSE.equals(user.getStatus())){
                Map<String,String> map = model.getMap();
                String sign = null;
                sign = map.get("sign");
                sign = sign.replaceAll("%2B","\\+");
                System.out.println(sign);
                map.remove("sign");
                byte[] data = null;
                boolean ver = false;
                try {
                    data = SignUtils.params(map).getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    throw new BaseException("签名校验过程异常！");
                }
                try {
                    ver=RSASignUtils.verify(data,user.getPublicKey(),sign);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BaseException("签名校验异常");
                }
                if (ver){
                    DaiFuOrder daiFuOrder = daiFuOrderService.submit(model);
                    witthdrawReturn.setMsg("下单成功！");
                    witthdrawReturn.setUserId(model.getUserId());
                    witthdrawReturn.setOrderNo(daiFuOrder.getOrderNo());
                    witthdrawReturn.setOutOrderNo(daiFuOrder.getOutOrderNo());
                    witthdrawReturn.setAmount(daiFuOrder.getAmount().toString());
                    witthdrawReturn.setTypeInfo(user.getIsAutoDf().toString());
                }else {
                    throw new BaseException("签名校验不通过！");

                }
            }
        }else {
            throw new BaseException("请填写完整参数！");
        }
        return witthdrawReturn;
    }

    @PostMapping("order_df")
    public QueryOrderDf queryOrderDf(OrderDf orderDf){
        QueryOrderDf queryOrderDf = new QueryOrderDf();
        if (!StringUtils.isEmpty(orderDf.getUserId()) && !StringUtils.isEmpty(orderDf.getOutOrderNo()) && !StringUtils.isEmpty(orderDf.getSign())) {
            User user = new User();
            user.setUsername(orderDf.getUserId());
            user = userService.findOne(user);
            if (!ObjectUtils.isEmpty(user)){
                if (StatusDict.NORMAL.equals(user.getStatus())){
                    Map<String,String> map = orderDf.getMap();
                    String sign = map.get("sign");
                    sign = sign.replaceAll("%2B","\\+");
                    map.remove("sign");
                    byte[] data = null;
                    try {
                        data = SignUtils.params(map).getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        throw new BaseException("签名校验过程异常！");
                    }
                    try {
                        if (RSASignUtils.verify(data,user.getPublicKey(),sign)){
                            DaiFuOrder daiFuOrder = new DaiFuOrder();
                            daiFuOrder.setOutOrderNo(orderDf.getOutOrderNo());
                            daiFuOrder = daiFuOrderService.findOne(daiFuOrder);
                            queryOrderDf.setAmount(daiFuOrder.getAmount());
                            queryOrderDf.setBank(daiFuOrder.getBank());
                            queryOrderDf.setCardNo(daiFuOrder.getCardNo());
                            queryOrderDf.setOrderNo(daiFuOrder.getOrderNo());
                            queryOrderDf.setOutOrderNo(daiFuOrder.getOutOrderNo());
                            queryOrderDf.setPerson(daiFuOrder.getPerson());
                            queryOrderDf.setStatus(daiFuOrder.getStatus().toString());
                            queryOrderDf.setUserId(orderDf.getUserId());
                            queryOrderDf.setPhone(daiFuOrder.getPhone());

                        }else {
                            throw new BaseException("验签失败！");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new BaseException("签名校验过程异常！");
                    }

                }else{
                    throw new BaseException("用户状态异常");
                }
            }else{
                throw new BaseException("用户不存在");
            }
        }else{
            throw new BaseException("请填写正确参数");
        }
        return queryOrderDf;
    }

    public boolean verifyNull(Object object){
        Class modelClz = object.getClass();

        Field[] fs = modelClz.getDeclaredFields();
        for (int i=0;i<fs.length;i++){
            Field field = fs[i];

            field.setAccessible(true);

            Object val = null;
            try {
                val = field.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (StringUtils.isEmpty(val)){
                return false;
            }
            log.info("key:"+field.getName());
            log.info("value:"+val);
        }

        return true;
    }






//    public Map getMap(Object object){
//        Map<String,String> map = new TreeMap();
//        Class modelClz = object.getClass();
//        Field[] fs = modelClz.getDeclaredFields();
//        for (int i=0;i<fs.length;i++){
//            Field field = fs[i];
//
//            field.setAccessible(true);
//
//            Object val = null;
//            try {
//                val = field.get(object);
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//            if (!StringUtils.isEmpty(val)){
//                map.put(field.getName(),val.toString());
//            }
//            log.info("key:"+field.getName());
//            log.info("value:"+val);
//        }
//        log.info(map.toString());
//        return map;
//    }
}
